package de.dopichaj.labrador.util.io;

import java.io.DataInput;
import java.io.EOFException;
import java.io.IOException;

import org.apache.log4j.Logger;

public final class BitInputStream {

    private static final Logger log = Logger.getLogger(BitInputStream.class);
    private final ByteReader input;
    private int bufferedBits;
    private int buffer;
    private long position;
    
    public BitInputStream(final ByteReader input) {
        this.input = input;
        this.bufferedBits = 0;
        this.position = 0;
    }
    
    public BitInputStream(final DataInput input) {
        this(new DataInputToByteReaderAdapter(input));
    }
    
    public int readBits(int bitCount) throws IOException {
        
        if (bitCount <= bufferedBits) {
            
            final int result = buffer & ((1 << bitCount) - 1);
            buffer >>= bitCount;
            bufferedBits -= bitCount;
            return result;
            
        } else {
            
            int currentBitCount = bitCount - bufferedBits;
            int resultBitCount = bufferedBits;
            int result = buffer;

            alwaysFillBuffer();
            while (currentBitCount > 8) {

                result |= buffer << resultBitCount;
                resultBitCount += 8;
                currentBitCount -= 8;
                alwaysFillBuffer();
            }
            result |= (buffer & ((1 << currentBitCount) - 1)) << resultBitCount;
            buffer >>= currentBitCount;
            bufferedBits -= currentBitCount;
            return result;
        }
    }

    public void skipToNext() {
        if (log.isDebugEnabled()) {
            log.debug("Ignoring " + bufferedBits + " bits.");
        }
        bufferedBits = 0;
    }
    
    private void fillBuffer() throws IOException, EOFException {
        if (bufferedBits == 0) {
            alwaysFillBuffer();
        }
    }

    private void alwaysFillBuffer() throws IOException, EOFException {
        buffer = input.readUnsignedByte();
        if (buffer == -1) {
            throw new EOFException();
        }
        bufferedBits = 8;
        position++;
    }

    public int readUnary() throws IOException {
        int value = 1;
        
        fillBuffer();
        
        while ((buffer & 1) == 1) {
        
            switch (buffer & 0xf) {
            case 0xf:
                bufferedBits -= 4;
                buffer >>= 4;
                value += 4;
                break;
            case 0x7:
                bufferedBits -= 3;
                buffer >>= 3;
                value += 3;
                break;
            case 0xb:
            case 0x3:
                bufferedBits -= 2;
                buffer >>= 2;
                value += 2;
                break;
            default:
                value++;
                bufferedBits--;
                buffer >>= 1;
            }
            fillBuffer();
        }
        buffer >>= 1;
        bufferedBits--;
        return value;
    }

    public int readGamma() throws IOException {

        final int log = readUnary() - 1;
        final int value = (1 << log) + readBits(log);
        return value;
    }


    public int readDelta() throws IOException {

        final int log = readGamma() - 1;
        final int value = (1 << log) + readBits(log);
        return value;
    }

    public int readVariableLengthInt() throws IOException {
        int value = 0;
        int shift = 0;
        do {
            final int bits = readBits(BitOutputStream.BITS_PER_BLOCK);
            value |= bits << shift;
            shift += BitOutputStream.BITS_PER_BLOCK;
            assert shift <= Integer.SIZE * 8;
        } while (readBits(1) == 1);
        return value;
    }
    
    public void readBytes(final byte[] bytes) throws IOException {
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte)readBits(8);
        }
    }

    public String readString() throws IOException {
        
        final int length = readGamma();
        final byte[] bytes = new byte[length];
        readBytes(bytes);
        return new String(bytes);
    }
    
    public long getPosition() {
        return position;
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/